package singleStep;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.File;
import java.io.IOException;

public class JsonPositionRemover {
    /**
     * 处理json数据,可任意删除字段
     * @param args
     */
    public static void main(String[] args) {
//        if (args.length < 2) {
//            System.out.println("Usage: java singleStep.JsonPositionRemover <inputFile> <outputFile>");
//            return;
//        }

        String inputFile = "D:\\code\\hdfork\\archguard\\server\\dependencies\\1_codes.json";
        String outputFile = "D:\\code\\hdfork\\archguard\\server\\dependencies\\codeCrop.json";

        try {
            ObjectMapper mapper = new ObjectMapper();

            // 读取JSON文件
            JsonNode rootNode = mapper.readTree(new File(inputFile));

            // 移除所有position字段
            removePositionFields(rootNode);

            // 写入处理后的JSON到输出文件
            mapper.writerWithDefaultPrettyPrinter().writeValue(new File(outputFile), rootNode);

            System.out.println("Successfully removed all position fields and saved to " + outputFile);
        } catch (IOException e) {
            System.err.println("Error processing JSON file: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void removePositionFields(JsonNode node) {
        if (node.isObject()) {
            ObjectNode objectNode = (ObjectNode) node;

            // 移除当前对象的position字段
            objectNode.remove("Position");
            objectNode.remove("Imports");
//            objectNode.remove("Annotations");
            objectNode.remove("Package");
            objectNode.remove("FilePath");
            objectNode.remove("Module");
            objectNode.remove("LocalVariables");
            objectNode.remove("Parameters");
//            objectNode.remove("Fields");

            // 递归处理所有子节点
            objectNode.fields().forEachRemaining(entry -> {
                removePositionFields(entry.getValue());
            });
        } else if (node.isArray()) {
            // 处理数组中的每个元素
            for (JsonNode arrayElement : node) {
                removePositionFields(arrayElement);
            }
        }
        // 其他类型的节点不需要处理
    }
}